package org.game.db;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import org.utils.RemoteUtil;

import com.sojoys.artifact.constant.ArtifactErrorCode;
import com.sojoys.artifact.factory.distributedId.IDistributedIdProvider;
import com.sojoys.artifact.manager.ThreadManager;
import com.sojoys.artifact.tools.ToolError;

/**
 * @author : DengYing
 * @CreateDate : 2017年10月16日 下午6:41:55
 * @Description ：玩家ID提供器
 */
public class PlayerIdProvider{

	private PlayerIdProvider() {
	}

	private static PlayerIdProvider ME = new PlayerIdProvider();

	public static PlayerIdProvider me() {
		return ME;
	}

	private ConcurrentLinkedQueue<Integer> primaryKeys = new ConcurrentLinkedQueue<>();
	private AtomicInteger primaryKeyCount = new AtomicInteger();

	

	public int pollId() {
		ToolError.isAndTrue(ArtifactErrorCode.SNOWFLAKE_ERROR, primaryKeys.isEmpty());
		int id = primaryKeys.poll();
		int count = primaryKeyCount.decrementAndGet();
		if (count < 8) {
			asynLoad();
		}
		return id;
	}
	
	public void syncLoad() {
		int[] pidPart = RemoteUtil.socialSync().getBatchPidPart(64);
		for (int pid = pidPart[0]; pid < pidPart[1]; pid++) {
			primaryKeys.add(pid);
		}
		primaryKeyCount.addAndGet(pidPart[1]-pidPart[0]);
		
	}
	
	public void asynLoad(){
		ThreadManager.me().execute("taskExecutor", () -> syncLoad());
	}
}
